package com.nari.kmd_dataservice.service.impl;

import com.nari.kmd_dataservice.constant.ConstantParameter;
import com.nari.kmd_dataservice.mapper.ServerMapper;
import com.nari.kmd_dataservice.pojo.dto.responseCons.ResponseConsListDataDto;
import com.nari.kmd_dataservice.pojo.dto.targetResponse.TargerResponseDto;
import com.nari.kmd_dataservice.pojo.entity.DeviceInfo;
import com.nari.kmd_dataservice.pojo.entity.LaUser;
import com.nari.kmd_dataservice.pojo.entity.ResponseEvent;
import com.nari.kmd_dataservice.pojo.entity.ResponseEventRange;
import com.nari.kmd_dataservice.pojo.request.targetResponse.RangeNoRequest;
import com.nari.kmd_dataservice.pojo.request.targetResponse.TargerResponseRequest;
import com.nari.kmd_dataservice.service.AutoServerService;
import com.nari.kmd_dataservice.service.LoadPlatformService;
import com.nari.kmd_dataservice.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName: ServerServiceImpl
 * @Description:
 * @Author: zhangnaijiang
 * @Date: 2022/02/16 14:07
 * @Version 1.0.0
 */
@Service
@Slf4j
public class AutoServerServiceImpl implements AutoServerService {
    @Resource
    private ServerMapper serverMapper;
    @Resource
    private LoadPlatformService loadPlatformService;

    @Override
    public void autoCreateEvent() {
        List<ResponseEvent> responseEventList = serverMapper.getNotPublishResponseEventList();
        if(CollectionUtils.isEmpty(responseEventList)){
//            insert into E_RESPONSE_EVENT(EVENT_ID, RESPONSE_TYPE, ACTIVE_TARGET, ACTIVE_START_TIME1, ACTIVE_END_TIME1) values('1001', '01', '1234.56', now(), now());

//            insert into E_RESPONSE_EVENT_RANGE(EVENT_ID, LA_REGIST_RATION_ID, ACTIVE_RANGE, RANGE_NO) values('1001', 'ddd567f8fc75b8be588a4b96c9b5a6d7545742b3bd588e366be0c4752349419d', '01', '13401');
//            insert into E_RESPONSE_EVENT_RANGE(EVENT_ID, LA_REGIST_RATION_ID, ACTIVE_RANGE, RANGE_NO) values('1001', 'ddd567f8fc75b8be588a4b96c9b5a6d7545742b3bd588e366be0c4752349419d', '02', '001');
            ResponseEvent responseEvent = new ResponseEvent();
            responseEvent.setReponseType("01");
            Random random = new Random();
            responseEvent.setActiveTarget(AlgorithmUtil.getPoint(random.nextDouble()*10000));
            responseEvent.setIsTest("1");
            responseEvent.setActiveStartTime1(LocalDateTimeUtil.getDateString(new Date(), ConstantParameter.dateFormatyyyyMMddHHmmss));
            responseEvent.setActiveEndTime1(LocalDateTimeUtil.getDateString(new Date(System.currentTimeMillis()+5*60*1000), ConstantParameter.dateFormatyyyyMMddHHmmss));
            responseEvent.setRespLimitTime(responseEvent.getActiveStartTime1());
            Integer eventId = serverMapper.addResponseEvent(responseEvent);
            if(eventId!=null){
                List<ResponseEventRange> responseEventRangeList = new ArrayList<>();
                /*所有负荷聚合平台的账号*/
                List<LaUser> laUserList = serverMapper.selectLaUserList();
                laUserList.forEach(item1->{
                    List<ResponseConsListDataDto> responseUsers = serverMapper.selectResponseConsList(item1.getLaRegistRationId());
                    responseUsers.forEach(item2->{
                        ResponseEventRange responseEventRange = new ResponseEventRange();
                        responseEventRange.setEventId(eventId+"");
                        responseEventRange.setLaRegistRationId(item1.getLaRegistRationId());
                        responseEventRange.setActiveRange("02");
                        responseEventRange.setRangeNo(item2.getConsNo());
                        responseEventRangeList.add(responseEventRange);
                    });
                });
                if (!CollectionUtils.isEmpty(responseEventRangeList)) {
                    log.info("新增需求响应事件的范围");
                    List<List<ResponseEventRange>> objListList = ObjConvertListUtil.splitArrayList(responseEventRangeList, 800);
                    for(List<ResponseEventRange> objList:objListList){
                        serverMapper.addResponseEventRangeList(objList);
                    }
                }
            }
        }
    }

    @Override
    public String autoTargetResponse() {
        List<ResponseEvent> responseEventList = serverMapper.getNotPublishResponseEventList();
        TargerResponseDto targerResponseDto = new TargerResponseDto();
        if(!CollectionUtils.isEmpty(responseEventList)){
            boolean allOk = true;
            String error = "";
            for(int i=0; i<responseEventList.size(); i++){
                ResponseEvent responseEvent = responseEventList.get(i);
                List<ResponseEventRange> responseEventRangeList = serverMapper.getNotPublishResponseEventRangeListByEventID(responseEvent.getEventId());
                //根据负荷聚合平台及范围拆分。
                if(!CollectionUtils.isEmpty(responseEventRangeList)){
                    Map<String, List<RangeNoRequest>> laRegistRationIdRangeNoMap = new HashMap<>();
                    for(int j=0; j<responseEventRangeList.size(); j++){
                        ResponseEventRange responseEventRange = responseEventRangeList.get(j);
                        String key = responseEventRange.getLaRegistRationId()+":"+responseEventRange.getActiveRange();
                        List<RangeNoRequest> rangeNoRequestList = laRegistRationIdRangeNoMap.get(key);
                        if(rangeNoRequestList==null){
                            rangeNoRequestList = new ArrayList<>();
                            laRegistRationIdRangeNoMap.put(key, rangeNoRequestList);
                        }
                        RangeNoRequest rangeNoRequest = new RangeNoRequest();
                        rangeNoRequest.setRangeNo(responseEventRange.getRangeNo());
                        rangeNoRequestList.add(rangeNoRequest);
                    }
                    for (Map.Entry<String, List<RangeNoRequest>> entry : laRegistRationIdRangeNoMap.entrySet()) {
                        String[] registRationIdActiveRange = entry.getKey().split(":");
                        String laRegistRationId = registRationIdActiveRange[0];
                        String activeRange = registRationIdActiveRange[1];
                        TargerResponseRequest targerResponseRequest = CopierUtil.copyProperties(responseEvent, TargerResponseRequest.class);
                        LaUser laUserPublish = serverMapper.selectLaUserByLaID(laRegistRationId);
                        if(laUserPublish==null){
                            log.error("负荷聚合平台注册ID:{}无对应聚合平台账号",laRegistRationId);
                            allOk = false;
                            error += ("负荷聚合平台注册ID:"+laRegistRationId+"无对应聚合平台账号")+";";
                            continue;
                        }
                        if(laUserPublish.getRegistRationId()==null){
                            log.error("负荷聚合平台注册ID:{}对应账号{}未认证",laRegistRationId, laUserPublish.getUserName());
                            allOk = false;
                            error += ("负荷聚合平台注册ID:"+laRegistRationId+"对应账号"+laUserPublish.getUserName()+"未认证")+";";
                            continue;
                        }
                        targerResponseRequest.setRegistRationId(laUserPublish.getRegistRationId());
                        targerResponseRequest.setActiveRange(activeRange);
                        targerResponseRequest.setData(entry.getValue());
                        boolean isSuccess = loadPlatformService.publishResponseEvent(targerResponseRequest);
                        if(!isSuccess){
                            allOk = false;
                        }
                    }
                }
                else{
                    log.error("事件编号{}无对应发布范围", responseEvent.getEventId());
                    allOk = false;
                    error += ("事件编号"+responseEvent.getEventId()+"无对应发布范围")+";";
                    continue;
                }
            }
            if(allOk){
                targerResponseDto.setStatus("01");
                targerResponseDto.setEventId("all");
            }
            else{
                targerResponseDto.setStatus("02");
                targerResponseDto.setEventId(error);
            }
            return GsonUtils.toJsonWtihNullField(targerResponseDto);
        }
        else{
            log.info("无未发布事件");
            targerResponseDto.setStatus("02");
            targerResponseDto.setEventId("无未发布事件");
            return GsonUtils.toJsonWtihNullField(targerResponseDto);
        }
    }

    @Override
    public void autoCheckResponseEvent() {
        serverMapper.updatePublishResponseEventEnd();
    }
}
